use anyhow::Result;
use clap::Parser;
use cli::{Cli, Commands};
use command::alter::AlterType;
use conf::{
    config_main::RdnfConfig,
    repo_conf::{finalize_repos, RepoConfig},
};
use console::Term;
use flock::{is_already_running, lock_rpmdb};

use utils::check_root;
pub mod cache;
mod cli;
mod command;
mod conf;
mod default;
mod error;
mod flock;
mod hash;
mod i18n;
pub mod repo;
pub mod solve;
mod utils;
pub struct Rdnf {
    cli: Cli,
    conf: RdnfConfig,
    repo_confs: Vec<RepoConfig>,
    term: Term,
}
impl Rdnf {
    pub fn new() -> Result<Self> {
        is_already_running()?;
        lock_rpmdb()?;
        let cli = Cli::parse().init();
        let conf = RdnfConfig::read(&cli.config_file_path)?;
        let mut repo_confs = RepoConfig::read_all(&conf.config_main.repodir)?;
        finalize_repos(&cli, &conf, &mut repo_confs)?;
        let term = Term::stdout();
        Ok(Rdnf {
            cli,
            conf,
            repo_confs,
            term,
        })
    }
}
// #[tokio::main(flavor="current_thread")]
#[tokio::main]
async fn main() -> Result<()> {
    let mut rdnf = Rdnf::new()?;
    match rdnf.cli.command {
        Commands::Repolist(_) => rdnf.repo_list()?,
        Commands::Makecache => {
            rdnf.cli.refresh = true;
            let _repos =
                Rdnf::make_cache(rdnf.repo_confs, rdnf.conf.config_main, rdnf.cli, rdnf.term)
                    .await?;
        }
        Commands::Install(ref alter) => {
            check_root()?;
            let pkgs = alter.pkgs.clone();
            let alter_arg = alter.clone();
            Rdnf::alter_command(rdnf, pkgs, AlterType::Install, alter_arg).await?;
        }
        // Commands::Makecache()=>rdnf.make_cache()?,
        _ => {}
    }
    Ok(())
    // println!("Hello, world!");
}
#[test]
fn verify_cli() {
    use clap::CommandFactory;
    Cli::command().debug_assert();
}

#[cfg(test)]
mod tests {
    use anyhow::Result;
    use assert_cmd::Command;
    fn get_cmd() -> Result<Command> {
        Ok(Command::cargo_bin("rdnf")?)
    }
    #[test]
    fn test_repo_list() -> Result<()> {
        let mut cmd = get_cmd()?;
        cmd.arg("install");
        cmd.arg("389-ds-base");
        // cmd.arg("python3-ldap");
        // cmd.arg("vim-enhanced");
        // dbg!(cmd.ok());
        let p = String::from_utf8(cmd.output().unwrap().stderr).unwrap();
        println!(
            "{}
        ",
            p
        );
        Ok(())
    }
}
//ncurses-libs
